package network

import (
	"sync"
	"sync/atomic"

	"github.com/panjf2000/gnet/v2"
	"github.com/wzh200x/gateServer/network/codec"
	"github.com/wzh200x/hyperNexus/hyperNexusType"
)

// Connection 代表一个客户端连接
type Connection struct {
	ConnId hyperNexusType.TypeConnectId
	Conn   gnet.Conn
	// 可以在这里添加更多与连接相关的属性，例如用户ID等
}

// ConnectionManager 管理所有客户端连接
type ConnectionManager struct {
	AutoConnectId hyperNexusType.TypeConnectId
	connections   map[hyperNexusType.TypeConnectId]*Connection
	lock          sync.RWMutex
}

// NewConnectionManager 创建一个新的ConnectionManager
func NewConnectionManager() *ConnectionManager {
	return &ConnectionManager{
		connections: make(map[hyperNexusType.TypeConnectId]*Connection),
	}
}

// AddConnection 添加一个新的连接
func (cm *ConnectionManager) AddConnection(conn gnet.Conn) {
	cm.lock.Lock()
	defer cm.lock.Unlock()

	connection := &Connection{
		ConnId: atomic.AddInt32(&cm.AutoConnectId, 1),
		Conn:   conn,
	}
	cm.connections[connection.ConnId] = connection
	codec := codec.NewCodec(connection.ConnId)
	connection.Conn.SetContext(codec)
}

// RemoveConnection 移除一个连接
func (cm *ConnectionManager) RemoveConnection(connId hyperNexusType.TypeConnectId) {
	cm.lock.Lock()
	defer cm.lock.Unlock()

	delete(cm.connections, connId)
}

// GetConnection 获取一个连接
func (cm *ConnectionManager) GetConnection(connId hyperNexusType.TypeConnectId) *Connection {
	cm.lock.RLock()
	defer cm.lock.RUnlock()

	return cm.connections[connId]
}

// Count 返回当前连接数
func (cm *ConnectionManager) Count() int {
	cm.lock.RLock()
	defer cm.lock.RUnlock()

	return len(cm.connections)
}
